<template>
  <div class="topo-node-detail">
    <ga-drawer class="topo-node-drawer" width="75%" :visible="visible" @cancel="() => emits('on-close')" popup-container=".topo-node-detail">

      <template #header>
        <div class="flex-spb-center" style="width: 100%;">
          <div>
            <span @click="() => emits('on-close')"><icon-close /></span>
            <span>{{ drawerTitle }}</span>
          </div>
          <ga-space>
            <ga-range-picker showTime v-model="pickerValue" @change="onChangeDate" :style="{ width: '360px' }" />
            <ga-button @click="refresh"><template #icon>
                <icon-refresh />
              </template></ga-button>
          </ga-space>
        </div>
      </template>
      <ga-alert type="warning" class="mb12" v-show="hasException">{{ exceptionInfo.exceptionMsg?.join("；") }}
        {{ exceptionInfo.exceptionMsg?.length ? "；" : "" }}
        <span class="span_a" @click="() => activeTab = 'alarm'">
          {{ exceptionInfo.alarmMessages?.join("；") }}
        </span></ga-alert>
      <BorderBox wrapperStyle="margin-bottom: 16px;">
        <template v-slot:title_l>
          <div>
            详情
          </div>
        </template>
        <template v-slot:main_info>
          <ga-descriptions title="" :column="2">
            <ga-descriptions-item v-for="item of infoColumns" :label="item.label" :key="item.label">
              <div v-if="item.customKey === 'source'">
                <ga-tooltip v-for="node in srcNodes" :key="drawerType === 'pod' ? node.podName : node.workloadKey"
                  :content="drawerType === 'pod' ? node.podName : node.workloadName
                    ">
                  <ga-tag style="max-width: 80px;display: inline-block;margin-right: 4px;" :class="`text-ellipsis ${node.workloadKind === 'vm' ? '' : 'pointer'
                    }`">
                    {{ drawerType === "pod" ? node.podName : node.workloadName }}
                  </ga-tag>
                </ga-tooltip>
              </div>
              <span v-else>{{ item.value }}</span>
            </ga-descriptions-item>
          </ga-descriptions>
        </template>
      </BorderBox>

      <ga-tabs v-model="activeTab" lazy-load type="card-gutter" size="large">
        <ga-tab-pane v-for="(item, idx) in tabs" :key="item.key" :title="item.label">

          <component :is="item.name" v-bind="item.props" v-on="item.events || {}" :tab="activeTab" pageType="node"
            :visible="visible" :node="nodeInfo" :queryTime="selectTime" :type="drawerType" :srcNodes="srcNodes" />
        </ga-tab-pane>
      </ga-tabs>
    </ga-drawer>
  </div>
</template>
<script>
export default {
  name: 'TopoNodeDetail'
}
</script>
<script setup>
import { computed, onMounted, reactive, ref, toRef, toRefs, watch } from 'vue';
import { useRoute } from 'vue-router';
import useNodeInfo from './useNodeInfo';
import BorderBox from '@/components/BorderBox'
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash'
import { bus } from '@/utils/eventBus';
import useTab from './useTab';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  nodeInfo: {
    type: Object,
    default: () => ({})
  },
  srcNodes: {
    type: Array,
    default: () => []
  },
  drawerType: {
    type: String,
    default: 'workload'
  },
  apiType: {
    type: String,
    default: 'system'
  },
  defaultActiveKey: {
    type: String,
    default: 'net'
  },
  queryTime: {
    type: Object,
    default: () => ({})
  }
})
const emits = defineEmits(['on-close'])
const { query } = useRoute()
// const { nodeInfo, drawerType, srcNodes } = toRefs(props)
// console.log(nodeInfo, 'nodeInfo');
const exceptionInfo = reactive({
  exceptionMsg: [],
  alarmMessages: [],
})
const pickerValue = reactive([
  dayjs().subtract(1, "hour").valueOf(),
  dayjs().valueOf(),
])
const selectTime = computed(() => {
  const [from, to] = pickerValue

  return {
    from: dayjs(from).format('YYYY-MM-DD HH:mm:ss'),
    to: dayjs(to).format('YYYY-MM-DD HH:mm:ss')
  }
})
const drawerTitle = computed(() => {

  return props.drawerType === "workload" ? props.nodeInfo?.workloadName : props.nodeInfo?.podName
})

const hasException = computed(() => {
  return exceptionInfo.exceptionMsg?.length > 0 ||
    Boolean(
      exceptionInfo.alarmMessages && exceptionInfo?.alarmMessages?.length > 0
    );
})
const { systemId } = query
const activeTab = ref(props.defaultActiveKey || 'net')

const nodeDetail = useNodeInfo({ ...toRefs(props), selectTime, systemId })
const nodeInfo = toRef(props, 'nodeInfo')


const infoColumns = computed(() => {
  console.log(nodeInfo.value, 'nodeInfo', props.nodeInfo, nodeDetail);
  const baseInfoColumns = [{
    label: '所属集群',
    value: nodeInfo.value?.masterName || nodeInfo.value?.masterIp
  }, {
    label: '命名空间',
    value: nodeInfo.value.namespace
  }, {
    label: '页面统计数据源端',
    value: '',
    customKey: 'source'
  }]
  const workloadColumn = [{
    label: '副本数',
    value: `${nodeDetail.value?.readyReplicas || 0}/${nodeDetail.value?.replicas || 0}`
  }]
  const unVmColumn = [{
    label: '容器重启次数',
    value: nodeDetail.value?.restartCount || 0
  }]
  let columns = cloneDeep(baseInfoColumns)
  if (props.drawerType === 'workload' && props.nodeInfo?.workloadKind !== 'vm') {
    columns = columns.concat(workloadColumn)
  }
  if (props.nodeInfo.workloadKind !== 'vm') {
    columns = columns.concat(unVmColumn)
  }
  return columns
})
const tabs = useTab(toRefs(props))
console.log(tabs, 'tabs');

const refresh = () => {
  bus.emit('updateTopoNodeDetail')
}


const onChangeDate = (value, date, dateStr) => {
  if (!value) {
    return;
  }
  console.log(value, date, dateStr, 'change date', pickerValue);
  const [from, to] = value
  pickerValue[0] = dayjs(from).valueOf();
  pickerValue[1] = dayjs(to).valueOf()
}

</script>

<style scoped lang="scss">
.topo-node-detail {
  :deep(.garco-tabs-type-card-gutter > .garco-tabs-content){
    border: none;
  }
  :deep(.garco-tabs-nav-tab) {
    background-color: transparent !important;
  }

}
</style>
